﻿using hyjiacan.py4n;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using System.Windows.Forms;

namespace QuestionSearch
{
    public partial class FrmMain : Form
    {
        List<Question> _questions = new();

        public FrmMain()
        {
            InitializeComponent();
            InitQuestion();
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
        }

        void InitQuestion()
        {
            var strFile = File.ReadAllText(Path.Combine(Application.StartupPath, "questions.txt"));
            var lines = strFile.Split("\r\n\r\n");
            if (lines.Length > 0)
            {
                foreach (var line in lines)
                {
                    var ary = line.Split("\r\n");
                    if (ary.Length > 0)
                    {
                        var pinYin = Pinyin4Net.GetPinyin(ary[0], PinyinFormat.LOWERCASE, false, true, false);
                        pinYin = Regex.Replace(pinYin, "\\[|\\]|\\s", string.Empty);

                        _questions.Add(new Question
                        {
                            Title = ary[0],
                            TitlePinYin = pinYin,
                            Answer = string.Join("\r\n", ary[1..]),
                        });
                    }
                }
            }
        }

        private void TxSearch_TextChanged(object sender, EventArgs e)
        {
            if (txSearch.Text.Trim().Length > 0)
            {
                txResult.Clear();
                var results = _questions.Where(q => q.TitlePinYin.Contains(txSearch.Text.Trim()))
                    .Take(10)
                    .ToList();

                foreach (var item in results)
                {
                    txResult.AppendText(item.Title);
                    txResult.AppendText(Environment.NewLine);
                    txResult.AppendText(item.Answer);
                    txResult.AppendText(Environment.NewLine);
                    txResult.AppendText(Environment.NewLine);
                }
            }
        }
    }

    internal class Question
    {
        public string Title { get; set; }
        public string TitlePinYin { get; set; }
        public string Answer { get; set; }
    }
}
